<template>
  <div class="supplier-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>供应商档案管理</h2>
      <p>管理供应商基础信息，包括供应商资质、联系方式、合作历史等</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="供应商编码">
            <el-input v-model="searchForm.supplierCode" placeholder="请输入供应商编码" clearable />
          </el-form-item>
          <el-form-item label="供应商名称">
            <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称" clearable />
          </el-form-item>
          <el-form-item label="供应商类型">
            <el-select v-model="searchForm.supplierType" placeholder="请选择类型" clearable>
              <el-option label="生产厂家" value="manufacturer" />
              <el-option label="贸易商" value="trader" />
              <el-option label="代理商" value="agent" />
              <el-option label="服务商" value="service" />
            </el-select>
          </el-form-item>
          <el-form-item label="合作状态">
            <el-select v-model="searchForm.cooperationStatus" placeholder="请选择状态" clearable>
              <el-option label="正常合作" value="active" />
              <el-option label="暂停合作" value="suspended" />
              <el-option label="终止合作" value="terminated" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增供应商
      </el-button>
      <el-button type="success" @click="handleBatchImport">
        <el-icon><Upload /></el-icon>
        批量导入
      </el-button>
      <el-button type="warning" @click="handleBatchExport">
        <el-icon><Download /></el-icon>
        批量导出
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="supplierCode" label="供应商编码" width="120" sortable />
        <el-table-column prop="supplierName" label="供应商名称" min-width="180" />
        <el-table-column prop="supplierType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getSupplierTypeColor(row.supplierType)">{{ getSupplierTypeLabel(row.supplierType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="130" />
        <el-table-column prop="creditLevel" label="信用等级" width="100">
          <template #default="{ row }">
            <el-rate v-model="row.creditLevel" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column prop="cooperationStatus" label="合作状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getCooperationStatusColor(row.cooperationStatus)">
              {{ getCooperationStatusLabel(row.cooperationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" sortable />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 供应商详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="supplier-form"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商编码" prop="supplierCode">
                  <el-input v-model="formData.supplierCode" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-input v-model="formData.supplierName" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商类型" prop="supplierType">
                  <el-select v-model="formData.supplierType" :disabled="dialogMode === 'view'" style="width: 100%">
                    <el-option label="生产厂家" value="manufacturer" />
                    <el-option label="贸易商" value="trader" />
                    <el-option label="代理商" value="agent" />
                    <el-option label="服务商" value="service" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="信用等级" prop="creditLevel">
                  <el-rate v-model="formData.creditLevel" :disabled="dialogMode === 'view'" show-text />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合作状态" prop="cooperationStatus">
                  <el-select v-model="formData.cooperationStatus" :disabled="dialogMode === 'view'" style="width: 100%">
                    <el-option label="正常合作" value="active" />
                    <el-option label="暂停合作" value="suspended" />
                    <el-option label="终止合作" value="terminated" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" prop="creditCode">
                  <el-input v-model="formData.creditCode" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="联系信息" name="contact">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="formData.contactPerson" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="formData.contactPhone" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input v-model="formData.email" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="传真号码" prop="fax">
                  <el-input v-model="formData.fax" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="formData.address" :disabled="dialogMode === 'view'" />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="财务信息" name="finance">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankName">
                  <el-input v-model="formData.bankName" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="bankAccount">
                  <el-input v-model="formData.bankAccount" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="付款方式" prop="paymentMethod">
                  <el-select v-model="formData.paymentMethod" :disabled="dialogMode === 'view'" style="width: 100%">
                    <el-option label="现金" value="cash" />
                    <el-option label="银行转账" value="transfer" />
                    <el-option label="支票" value="check" />
                    <el-option label="承兑汇票" value="acceptance" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款周期(天)" prop="paymentCycle">
                  <el-input-number v-model="formData.paymentCycle" :disabled="dialogMode === 'view'" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="其他信息" name="other">
            <el-form-item label="主营产品" prop="mainProducts">
              <el-input
                v-model="formData.mainProducts"
                type="textarea"
                :rows="3"
                :disabled="dialogMode === 'view'"
                placeholder="请输入主营产品信息"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                :disabled="dialogMode === 'view'"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogMode !== 'view'" type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view
const selectedRows = ref([])
const formRef = ref()
const activeTab = ref('basic')

// 搜索表单
const searchForm = reactive({
  supplierCode: '',
  supplierName: '',
  supplierType: '',
  cooperationStatus: ''
})

// 表单数据
const formData = reactive({
  id: null,
  supplierCode: '',
  supplierName: '',
  supplierType: '',
  creditLevel: 3,
  cooperationStatus: 'active',
  creditCode: '',
  contactPerson: '',
  contactPhone: '',
  email: '',
  fax: '',
  address: '',
  bankName: '',
  bankAccount: '',
  paymentMethod: '',
  paymentCycle: 30,
  mainProducts: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  supplierCode: [
    { required: true, message: '请输入供应商编码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  supplierType: [
    { required: true, message: '请选择供应商类型', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 模拟数据
const mockData = [
  {
    id: 1,
    supplierCode: 'S001',
    supplierName: '深圳华强电子有限公司',
    supplierType: 'manufacturer',
    creditLevel: 5,
    cooperationStatus: 'active',
    creditCode: '91440300123456789X',
    contactPerson: '张经理',
    contactPhone: '13800138001',
    email: 'zhang@huaqiang.com',
    fax: '0755-12345678',
    address: '深圳市福田区华强北路1号',
    bankName: '中国银行深圳分行',
    bankAccount: '1234567890123456789',
    paymentMethod: 'transfer',
    paymentCycle: 30,
    mainProducts: '电子元器件、集成电路、传感器',
    remark: '长期合作伙伴，产品质量稳定',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    supplierCode: 'S002',
    supplierName: '上海纺织贸易公司',
    supplierType: 'trader',
    creditLevel: 4,
    cooperationStatus: 'active',
    creditCode: '91310000987654321Y',
    contactPerson: '李总',
    contactPhone: '13900139002',
    email: 'li@textile.com',
    fax: '021-87654321',
    address: '上海市黄浦区南京东路100号',
    bankName: '工商银行上海分行',
    bankAccount: '9876543210987654321',
    paymentMethod: 'acceptance',
    paymentCycle: 60,
    mainProducts: '棉纺织品、化纤面料、服装辅料',
    remark: '价格优势明显，交货及时',
    createTime: '2024-01-16 14:20:00'
  },
  {
    id: 3,
    supplierCode: 'S003',
    supplierName: '北京食品供应链有限公司',
    supplierType: 'agent',
    creditLevel: 4,
    cooperationStatus: 'active',
    creditCode: '91110000456789123Z',
    contactPerson: '王主任',
    contactPhone: '13700137003',
    email: 'wang@foodchain.com',
    fax: '010-12345678',
    address: '北京市朝阳区建国门外大街1号',
    bankName: '建设银行北京分行',
    bankAccount: '5555666677778888999',
    paymentMethod: 'cash',
    paymentCycle: 15,
    mainProducts: '冷冻食品、调味品、包装材料',
    remark: '食品安全认证齐全',
    createTime: '2024-01-17 09:15:00'
  },
  {
    id: 4,
    supplierCode: 'S004',
    supplierName: '广州物流服务公司',
    supplierType: 'service',
    creditLevel: 3,
    cooperationStatus: 'suspended',
    creditCode: '91440100789123456A',
    contactPerson: '陈队长',
    contactPhone: '13600136004',
    email: 'chen@logistics.com',
    fax: '020-87654321',
    address: '广州市天河区珠江新城2号',
    bankName: '农业银行广州分行',
    bankAccount: '1111222233334444555',
    paymentMethod: 'transfer',
    paymentCycle: 7,
    mainProducts: '货物运输、仓储服务、配送服务',
    remark: '因服务质量问题暂停合作',
    createTime: '2024-01-18 16:45:00'
  },
  {
    id: 5,
    supplierCode: 'S005',
    supplierName: '杭州家具制造厂',
    supplierType: 'manufacturer',
    creditLevel: 5,
    cooperationStatus: 'active',
    creditCode: '91330100654321987B',
    contactPerson: '刘厂长',
    contactPhone: '13500135005',
    email: 'liu@furniture.com',
    fax: '0571-12345678',
    address: '杭州市西湖区文三路100号',
    bankName: '招商银行杭州分行',
    bankAccount: '7777888899990000111',
    paymentMethod: 'check',
    paymentCycle: 45,
    mainProducts: '办公家具、实木家具、定制家具',
    remark: '环保材料，工艺精良',
    createTime: '2024-01-19 11:30:00'
  }
]

// 方法
const getSupplierTypeColor = (type) => {
  const colors = {
    manufacturer: 'primary',
    trader: 'success',
    agent: 'warning',
    service: 'info'
  }
  return colors[type] || 'info'
}

const getSupplierTypeLabel = (type) => {
  const labels = {
    manufacturer: '生产厂家',
    trader: '贸易商',
    agent: '代理商',
    service: '服务商'
  }
  return labels[type] || type
}

const getCooperationStatusColor = (status) => {
  const colors = {
    active: 'success',
    suspended: 'warning',
    terminated: 'danger'
  }
  return colors[status] || 'info'
}

const getCooperationStatusLabel = (status) => {
  const labels = {
    active: '正常合作',
    suspended: '暂停合作',
    terminated: '终止合作'
  }
  return labels[status] || status
}

const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    let filteredData = [...mockData]
    
    if (searchForm.supplierCode) {
      filteredData = filteredData.filter(item => 
        item.supplierCode.toLowerCase().includes(searchForm.supplierCode.toLowerCase())
      )
    }
    
    if (searchForm.supplierName) {
      filteredData = filteredData.filter(item => 
        item.supplierName.toLowerCase().includes(searchForm.supplierName.toLowerCase())
      )
    }
    
    if (searchForm.supplierType) {
      filteredData = filteredData.filter(item => item.supplierType === searchForm.supplierType)
    }
    
    if (searchForm.cooperationStatus) {
      filteredData = filteredData.filter(item => item.cooperationStatus === searchForm.cooperationStatus)
    }
    
    tableData.value = filteredData
    pagination.total = filteredData.length
    loading.value = false
    
    ElMessage.success('搜索完成')
  }, 500)
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  loadData()
}

const handleAdd = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增供应商'
  activeTab.value = 'basic'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑供应商'
  activeTab.value = 'basic'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogMode.value = 'view'
  dialogTitle.value = '查看供应商详情'
  activeTab.value = 'basic'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除供应商 "${row.supplierName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的供应商')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个供应商吗？`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟批量删除
    const selectedIds = selectedRows.value.map(row => row.id)
    tableData.value = tableData.value.filter(item => !selectedIds.includes(item.id))
    pagination.total -= selectedRows.value.length
    selectedRows.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

const handleBatchExport = () => {
  ElMessage.info('批量导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (dialogMode.value === 'add') {
        // 模拟新增
        const newSupplier = {
          ...formData,
          id: Date.now(),
          createTime: new Date().toLocaleString()
        }
        tableData.value.unshift(newSupplier)
        pagination.total++
        ElMessage.success('新增成功')
      } else if (dialogMode.value === 'edit') {
        // 模拟编辑
        const index = tableData.value.findIndex(item => item.id === formData.id)
        if (index > -1) {
          Object.assign(tableData.value[index], formData)
          ElMessage.success('编辑成功')
        }
      }
      dialogVisible.value = false
    }
  })
}

const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    supplierCode: '',
    supplierName: '',
    supplierType: '',
    creditLevel: 3,
    cooperationStatus: 'active',
    creditCode: '',
    contactPerson: '',
    contactPhone: '',
    email: '',
    fax: '',
    address: '',
    bankName: '',
    bankAccount: '',
    paymentMethod: '',
    paymentCycle: 30,
    mainProducts: '',
    remark: ''
  })
}

const loadData = () => {
  loading.value = true
  // 模拟加载数据
  setTimeout(() => {
    tableData.value = [...mockData]
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.supplier-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}

.supplier-form {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .supplier-management {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .action-section .el-button {
    width: 100%;
  }
}
</style>